package jfdi;

import android.util.JsonReader;

import util.Mlog;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class JsonLoader {

    public static final String TYPE = "type";
    public static final String NODES = "nodes";

    public static Node loadLayout(NodeHost host, int id) {
        try {
            JsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(host.getResources().openRawResource(id))));
            reader.setLenient(true);
            return readNode(host, reader);
        } catch (IOException iox) {
            Mlog.i("json", "error : ", iox);
            return null;
        } catch (IllegalStateException ise) {
            Mlog.i("json", "error parsing at ", ise);
            return null;
        }
    }

    private static Node initType(NodeHost host, String type) {
        Mlog.i("json", "create node of type: ", type);
        if ("group".equals(type)) {
            return new NodeGroup(host);
        } else if ("label".equals(type)) {
            return new Label(host);
        } else if ("button".equals(type)) {
            return new Button(host);
        } else if ("drag".equals(type)) {
            return new DragNode(host);
        }
        return null;
    }

    public static Node readNode(NodeHost host, JsonReader reader) throws IOException {
        Mlog.i("json", "building node");
        Node result = null;
        reader.beginObject();
        while (reader.hasNext()) {
            String attr = reader.nextName();
            Mlog.i("json", "attribute: ", attr);
            if (TYPE.equals(attr)) {
                result = initType(host, reader.nextString());
            } else {
                result.setAttribute(host, attr, reader);
            }
        }
        reader.endObject();
        return result;
    }

}
